package com.zengqingfa.algorithm.cz.chapter02;

import java.util.Arrays;

/**
 * @author zengqingfa
 * @className BubbleSort
 * @description
 * @create 2021/8/6 11:25
 */
public class BubbleSort {

    public static void main(String[] args) {
        Integer[] arr={2,3,6,4,5,7,1};
        sort(arr);
        System.out.println(Arrays.toString(arr));

    }

    public static void sort(Comparable[] arr) {
        //n个数，需要冒泡n次
        for (int i = 0; i < arr.length; i++) {
            //每冒泡一次，比较的次数-1
            for (int j = 0; j < arr.length - i-1 ; j++) {
                //判断当前值和后面一个值的大小关系
                if(greater(arr[j],arr[j+1])){
                    swap(arr,j,j+1);
                }
            }
        }
    }

    /**
     * 判断a是否大于b
     *
     * @param a
     * @param b
     * @return
     */
    public static boolean greater(Comparable a, Comparable b) {
        return a.compareTo(b) > 0;
    }

    /**
     * 交换数组中索引a和b中元素的值
     *
     * @param arr
     * @param a
     * @param b
     */
    public static void swap(Comparable[] arr, int a, int b) {
        Comparable temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }


}